//
//  KWMAPIManager.m
//  iXiaoWeiOA
//
//  Created by kevin on 3/14/15.
//  Copyright (c) 2015 kollway. All rights reserved.
//

#import "KWMAPIManager.h"
#import "KWMStringUtil.h"
#import "KWMUserDao.h"
#import "KWMUser.h"

// 获取Mac Address
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@interface KWMAPIManager()

@property(nonatomic) NSString *sessionId;

@end


@implementation KWMAPIManager


+ (KWMAPIManager *)sharedManager {
    static KWMAPIManager *_sharedManager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (NSString *)toAbsoluteUrl:(NSString *)relativeUrl {
    if([KWMStringUtil isEmpty:relativeUrl]){
        return self.baseUrl;
    }
    if([relativeUrl rangeOfString:@"http"].location == 0){
        return relativeUrl;
    }
    return [[NSString alloc] initWithFormat:@"%@%@", self.baseUrl, relativeUrl];
}

- (NSString *)baseUrl {
    if(! _baseUrl){
        _baseUrl = [[NSString alloc] initWithFormat:@"http://%@", API_HOST];
    }
    return _baseUrl;
}

/**
 * 从KWMUserDao获取
 */
- (NSString *)sessionId {
    return [KWMUserDao shareDao].sessionId;
}

#pragma mark - /UserApi

- (void)fetchSession:(NSHTTPURLResponse *)httpResponse user:(KWMUser *)user {
    //获取最新的Cookie
    NSString *auth = nil;
    
    NSString *setCookieStr = httpResponse.allHeaderFields[@"Set-Cookie"];
    if (![KWMStringUtil isEmpty:setCookieStr]) {
        NSRange range1 = [setCookieStr rangeOfString:@"="];
        NSRange range2 = [setCookieStr rangeOfString:@";"];
        NSInteger len = range2.location - range1.location;
        NSInteger loc = range1.location + 1;
        if (len > 0) {
            auth = [setCookieStr substringWithRange:NSMakeRange(loc, len)];
        }
    }
    
    //保存用户和Cookie
    KWMUserDao *userDao = [KWMUserDao shareDao];
    [userDao setLoginUser:(KWMUser *)user :auth];
}



@end
